<?php
/**
 * Created by PhpStorm.
 * User: sosyuki
 * Date: 2018/6/4
 * Time: 14:21
 */

namespace Drupal\newmenu;


use Exception;

class newmenuServicesController {

  protected $mini;

  public function __construct() {
    $this->mini = wx_mini_program_get_app();
    return $this;
  }

  function set_user_info($iv, $encrypted) {
    try {
      global $user;
      $mini = $this->mini;
      $sessionKey = $this->getSessionKey($user->uid);
      $decrypted = $mini->encryptor->decryptData($sessionKey, $iv, $encrypted);
      $nickName = $decrypted['nickName'];
      $sex = $decrypted['gender'];
      $dir = 'public://pictures/';
      $userWrapper = entity_metadata_wrapper('user', $user);
      if (empty($userWrapper->field_avatar->value())) {
        $result = file_prepare_directory($dir);
        if (!$result) {
          drupal_mkdir($dir);
        }
        $destination = $dir . $decrypted['openId'] . '.png';
        $file = file_save_data(file_get_contents($decrypted['avatarUrl']), $destination, FILE_EXISTS_REPLACE);
        $userWrapper->field_avatar->set(['fid' => $file->fid]);
      }
      $userWrapper->field_nickname->set($nickName);
      $userWrapper->field_sex->set($sex);
      $userWrapper->save();
      return [
        'code' => 0,
        'msg' => 'ok',
      ];
    } catch (Exception $e) {
      watchdog_exception(__FUNCTION__, $e);
      return [
        'code' => 1,
        'msg' => '系统错误',
      ];
    }
  }

  protected function getSessionKey($uid) {
    return wx_mini_program_get_session_key($uid);
  }

  function set_user_phone($iv, $encrypted) {
    try {
      global $user;
      $mini = $this->mini;
      $sessionKey = $this->getSessionKey($user->uid);
      $decrypted = $mini->encryptor->decryptData($sessionKey, $iv, $encrypted);
      $phoneNumber = $decrypted['phoneNumber'];
      $userWrapper = entity_metadata_wrapper('user', $user);
      $userWrapper->field_phone->set($phoneNumber);
      $userWrapper->save();
      return [
        'code' => 0,
        'msg' => 'ok',
      ];
    } catch (Exception $e) {
      watchdog_exception(__FUNCTION__, $e);
      return [
        'code' => 1,
        'msg' => '系统错误',
      ];
    }
  }

}
